﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Threading;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Co=Code.Models;
using Code.Commen;
using Code.BLL;

using Op = OpenCode;
using System.Data.SqlClient;

namespace QianBuo.Lottery.Server
{

    /// <summary>
    /// Task 的摘要说明
    /// </summary>
    internal class BackTask
    {

        #region 私有成员

        private Thread thread;

        private static BackTask _OpenWin;

        /// <summary>
        /// 0 停止 1 运行中 2 置为停止
        /// </summary>
        private int State = 0;

        /// <summary>
        /// 当前已开的期号
        /// </summary>
        private IDictionary<Co.LotteryType, Co.Issue> CurrentIssue;
        /// <summary>
        /// 期号管理
        /// </summary>
        private IssueManage IM = new IssueManage();
        private LotteryManage LM = new LotteryManage();
        /// <summary>
        /// 日志记录
        /// </summary>
        private log4net.ILog Log = Code.Commen.Log.GetLog(typeof(BackTask));
        #endregion

        #region 构造方法

        /// <summary>
        /// 获取当前的开奖对象
        /// </summary>
        public static BackTask Current
        {
            get
            {
                if (_OpenWin == null)
                    _OpenWin = new BackTask();
                return _OpenWin;
            }
        }

        /// <summary>
        /// 构造涵数
        /// </summary>
        private BackTask() { }

        private void Init()
        {
            CurrentIssue = new Dictionary<Co.LotteryType, Co.Issue>();
            try
            {
                var lotts = CacheManage.Lottery.Keys;
                foreach (var item in lotts)
                {
                    CurrentIssue.Add(item, IM.GetPriorIssue(item));
                }

                if (CacheManage.OptionSite[Co.Option_Site_Key.Site_Lottery_AutoCancleTimeOutScheme].ToBool(false))
                    new SchemeManage().CancleTimeOutSchemes();
            }
            catch (SqlException)
            {
            }
            catch (Exception) 
            { }

        }
        #endregion

        #region 公有方法
        public void Run()
        {
            // 已经启动
            if (State == 1)
            {
                return;
            }

            lock (this) // 确保临界区被一个 Thread 所占用
            {
                State = 1;

                thread = new Thread(new ThreadStart(Do));
                thread.Start();
            }
        }

        public void Exit()
        {
            State = 2;
        }

        public void Do()
        {
            Init();

            int count = CurrentIssue.Count;
            var keys = CurrentIssue.Keys.ToArray();
            while (true)
            {
                if (State == 2) //停止开奖
                {
                    Thread.CurrentThread.Abort();
                    return;
                }

                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        var l=CacheManage.Lottery[keys[i]];
                        if (l.State == (short)Co.LotteryState.Locked)
                            continue;

                        var issue = CurrentIssue[keys[i]];

                        if (issue == null)    //无上期信息
                        {
                            issue = IM.GetPriorIssue((Co.LotteryType)l.ID);

                            if (issue == null)
                                continue;

                            CurrentIssue[keys[i]] = issue;
                        }

                        if (issue.State == (short)Co.IssueState.Opened)
                        {
                            issue = IM.GetNextIssue((Co.LotteryType)l.ID, issue.StartTime);
                            CurrentIssue[keys[i]] = issue;
                        }
                        if (issue == null)
                            continue;

                        //该期已截止
                        if ((Co.IssueState)issue.State == Co.IssueState.Normal && issue.EndTime < DateTime.Now)
                        {
                            OpenWin ow = new OpenWin(l, issue);
                            OutBill ob = new OutBill(l, issue);
                            
                            Thread outbill = new Thread(new ThreadStart(ob.Do));
                            outbill.Start();

                            Thread opwin = new Thread(new ThreadStart(ow.DoOpen));
                            opwin.Start();

                            CurrentIssue[keys[i]] = IM.GetNextIssue(keys[i], issue.StartTime);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (Log.IsDebugEnabled)
                        Log.Debug("开奖出错", e);
                    else if (Log.IsInfoEnabled)
                        Log.Info("开奖出错:"+e.Message);
                }

                if (State == 2) //停止开奖
                {
                    Thread.CurrentThread.Abort();
                    return;
                }

                Thread.Sleep(5000);
            }
        }
        #endregion
    }



}